package com.zzyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WechatServiceImpl implements WechatService {

    //获得openid的地址
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    //获得手机号令牌的地址
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    //获得手机号的地址
    private static final  String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${zzyl.wechat.appId}")
    private String appId;
    @Value("${zzyl.wechat.appSecret}")
    private String appSecret;

    @Override
    public String getOpenId(String code) {
        //1.封装3个请求参数Map<String,Object>
        HashMap<String, Object> map = new HashMap<>();
        map.put("js_code",code);
        map.put("appid",appId);
        map.put("secret",appSecret);
        //2.远程调用返回json字符串
        String result = HttpUtil.get(REQUEST_URL, map);
        //3.将json字符串转换为JsonObject对象（就是map）
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //4.判断是否发生错误，如果有错误抛出异常
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(BasicEnum.GET_OPENID_ERROR);
        }
        //5.没有错误，返回openid
        return jsonObject.getStr("openid");
    }

    //获取手机号
    @Override
    public String getPhone(String code) {

        String token = getToken(code);
        //1.封装3个请求参数Map<String,Object>
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        //2.远程调用返回json字符串
        String result = HttpUtil.post(PHONE_REQUEST_URL + token, JSONUtil.toJsonStr(map));
        //3.将json字符串转换为JsonObject对象（就是map）
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //4.判断是否发生错误，如果有错误抛出异常
        if (jsonObject.get("errcode") != null && jsonObject.getInt("errcode") != 0){
            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
        }
        //5.没有错误，返回openid
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    //获取手机号的令牌
    public String getToken(String code) {
        //1.封装3个请求参数Map<String,Object>
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid",appId);
        map.put("secret",appSecret);
        //2.远程调用返回json字符串
        String result = HttpUtil.get(TOKEN_URL, map);
        //3.将json字符串转换为JsonObject对象（就是map）
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //4.判断是否发生错误，如果有错误抛出异常
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
        }
        //5.没有错误，返回openid
        return jsonObject.getStr("access_token");
    }
}